package com.sgzn.sgpay.service.tcp.receive;

import com.sgzn.sgpay.enums.RespResultEnum;
import com.sgzn.sgpay.service.tcp.receive.modle.TcpReceiveCallRequest;
import lombok.extern.slf4j.Slf4j;

/**
 * Tcp 响应模板类
 * @author huangsenguang
 * @version Id: TcpReceiveCallHandleTemplate.java, v 0.1 2018/7/29 15:11 huangsenguang Exp $$
 */
@Slf4j
public abstract class TcpReceiveCallHandlerTemplate<T> implements TcpReceiveCallHandler {
    @Override
    public void handle(TcpReceiveCallRequest request) {
        try {
            handleBefore(request);
            T result =  callInner(request);
            log.info("设备id:{}; 请求流水：{}; {}data处理结果:{}", request.getDeviceId(),request.getReqSeq(),request.getCmdName(), result.toString());
            handleAfter(request, result);
        } catch (Exception e) {
            log.error("Tcp接收终端报文处理异常:", e);
        }
    }

    /**
     * 处理前
     * @param request
     */
    protected void handleBefore(TcpReceiveCallRequest request){
        //校验
        String protocolContext = request.getProtocolContext();
        int length = protocolContext.length();
        if (length != getProtocolLength(request)) {
            log.info("{}协议长度不匹配{}，{}",request.getCmdName(), getProtocolLength(request), length);
            throw new RuntimeException("协议长度不匹配");
        }
        String data = protocolContext.substring(8, length - 3);
        log.info("data:{}", data);
        request.setData(data);
    }

    /**
     * 解析处理协议data
     * @param request
     * @return 解析后结果
     */
    protected abstract T callInner(TcpReceiveCallRequest request);

    /**
     * 处理后
     * @param request
     * @param result
     */
    protected void handleAfter(TcpReceiveCallRequest request, T result) {
        //有需要对响应结果处理， 请重写此方法
    }

    /**
     * 获取协议总字符数
     * @return
     */
    protected abstract int getProtocolLength(TcpReceiveCallRequest request);


    /**
     * 判断是否成功
     * 0：失败  1：成功
     * @param request
     * @return
     */
    protected boolean isSuccess(TcpReceiveCallRequest request) {
        if (RespResultEnum.SUCCESS.getCode().equals(request.getData().substring(1,2))) {
            log.info("设备id:{}; 请求流水：{}; {}成功 true:{}", request.getDeviceId(),request.getReqSeq(),request.getCmdName(), RespResultEnum.SUCCESS.getCode());
            return true;
        }
        log.info("设备id:{}; 请求流水：{}; {}失败 false:{}", request.getDeviceId(), request.getReqSeq(),request.getCmdName(), RespResultEnum.FAIL.getCode());
        return false;
    }
}

